#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "singleton.hpp"
#include "Json.h"
#include "Logger.h"
#include "server.h"

using namespace dxy::easyWebServer;
using namespace easyWebServer;

int main(int argc, char * argv[])
{

    bool isDaemon               = false;
    std::string confPath        = "/etc/easyWebServer/config.conf";
    int c;
    while((c = getopt(argc, argv, "dc:")) != -1)
    {
        switch (c)
        {
        case 'd':
            isDaemon = true;
            break;
        case 'c':
            confPath = optarg;
        default:
            break;
        }
    }

    if(isDaemon)
    {
        pid_t pid = fork();
        if (pid > 0)
        {
            exit(EXIT_SUCCESS);
        }
    }

    slt(Json).parseFromFile(confPath);
    chdir(slt(Json)["root"].asString().c_str());
    mkdir("./logs", S_IRWXU);

    Logger::instance()->open("./logs/webServerLog.log");
    Logger::instance()->level(Logger::INFO);
    Logger::instance()->isTermial(false);
    Logger::instance()->max(10240);

    try
    {
        Server server;
        server.init();
        server.start();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }

    return 0;
}